package com.pureut.quality.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pureut.common.core.exception.GlobalException;
import com.pureut.common.core.utils.StringUtils;
import com.pureut.common.datascope.annotation.DataScope;
import com.pureut.common.security.utils.DictUtils;
import com.pureut.common.security.utils.SecurityUtils;
import com.pureut.quality.domain.QualityBadCategory;
import com.pureut.quality.domain.dto.QualityBadCategoryDto;
import com.pureut.quality.domain.vo.QualityBadCategoryVo;
import com.pureut.quality.export.QualityBadCategoryExport;
import com.pureut.quality.mapper.QualityBadCategoryMapper;
import com.pureut.quality.service.IQualityBadCategoryService;
import com.pureut.system.api.FeignService;
import com.pureut.system.api.domain.SysDictData;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description 不良类别实现类
 * @Param
 * @Date 23-02-02
 * @Author hl
 **/
@Service
public class QualityBadCategoryServiceImpl extends ServiceImpl<QualityBadCategoryMapper, QualityBadCategory> implements IQualityBadCategoryService {

    @Resource
    private QualityBadCategoryMapper qualityBadCategoryMapper;

    @Resource
    FeignService feignService;

    /**
     * 查询不良类别
     *
     * @param qualityBadCategoryVo 不良类别接受类
     * @return List
     */
    @Override
    @DataScope(deptAlias = "quality_bad_category")
    public List<QualityBadCategoryDto> selectBadCategoryList(QualityBadCategoryVo qualityBadCategoryVo) {
        List<QualityBadCategoryDto> list = qualityBadCategoryMapper.selectBadCategoryList(qualityBadCategoryVo);

        //检测阶别
        List<SysDictData> rankArray = DictUtils.getDictCache("item_rank");
        Map<String, String> rankMap = rankArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //不良等级
        List<SysDictData> badLevelArray = DictUtils.getDictCache("quality_bad_level");
        Map<String, String> badLevelMap = badLevelArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        for (QualityBadCategoryDto entity : list) {
            //检测阶别
            entity.setItemRankDict(rankMap.get(entity.getItemRank()));
            //不良等级
            entity.setBadGradeDict(badLevelMap.get(entity.getBadGrade()));
        }
        return list;
    }

    /**
     * 新增不良类别
     *
     * @param qualityBadCategoryVo 不良类别接受类
     * @return int 1 成功 0 失败
     */
    @Override
    public boolean insertBadCategory(QualityBadCategoryVo qualityBadCategoryVo) throws Exception {


        QualityBadCategory qualityBadCategory = new QualityBadCategory();
        String authorityCoding = feignService.getAuthorityCoding("quality:verifyconfig:badcategory:list");
        if (authorityCoding == null) {
            throw new GlobalException("该单据未进行配置，无法生成单据编码");
        }
        qualityBadCategory.setBadCode(authorityCoding)
                .setBadName(qualityBadCategoryVo.getBadName())
                .setBadContent(qualityBadCategoryVo.getBadContent())
                .setBadGrade(qualityBadCategoryVo.getBadGrade())
                .setItemRank(qualityBadCategoryVo.getItemRank())
                .setCreateTime(new Date())
                .setDeptId(SecurityUtils.getDeptId());

        return save(qualityBadCategory);
    }

    /**
     * 批量删除不良类别
     *
     * @param badId id
     * @return int 1 成功 0 失败
     */
    @Override
    public int deleteBadCategoryById(String badId) {
        String[] badIdS = badId.split(",");
        return qualityBadCategoryMapper.deleteBadCategoryById(badIdS);
    }

    /**
     * 查询单个不良类别
     *
     * @param badId id
     * @return QualityBadCategoryDto 不良类别返回类
     */
    @Override
    public QualityBadCategoryDto selectBadCategoryById(long badId) {
        QualityBadCategoryVo vo = new QualityBadCategoryVo();
        vo.setBadId(badId);
        List<QualityBadCategoryDto> list = qualityBadCategoryMapper.selectBadCategoryList(vo);
        //检测阶别
        List<SysDictData> rankArray = DictUtils.getDictCache("item_rank");
        Map<String, String> rankMap = rankArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //不良等级
        List<SysDictData> badLevelArray = DictUtils.getDictCache("quality_bad_level");
        Map<String, String> badLevelMap = badLevelArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        QualityBadCategoryDto qualityBadCategoryDto = list.get(0);
        //检测阶别
        qualityBadCategoryDto.setItemRankDict(rankMap.get(qualityBadCategoryDto.getItemRank()));
        //不良等级
        qualityBadCategoryDto.setBadGradeDict(badLevelMap.get(qualityBadCategoryDto.getBadGrade()));
        return qualityBadCategoryDto;
    }

    /**
     * 修改不良类别
     *
     * @param qualityBadCategoryVo 不良类别接受类
     * @return int 1 成功 0 失败
     */
    @Override
    public boolean updateBadCategoryEdit(QualityBadCategoryVo qualityBadCategoryVo) {
        QualityBadCategory byId = getById(qualityBadCategoryVo.getBadId());
        byId.setItemRank(qualityBadCategoryVo.getItemRank())
                .setBadContent(qualityBadCategoryVo.getBadContent())
                .setBadName(qualityBadCategoryVo.getBadName())
                .setBadGrade(qualityBadCategoryVo.getBadGrade());
        return updateById(byId);
    }

    /**
     * 导入
     * @param coCustomer
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importMouldData(List<QualityBadCategoryExport> coCustomer) {
        if (StringUtils.isNull(coCustomer) || coCustomer.size() == 0) {
            throw new GlobalException("导入不良类别信息不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();


        //检测阶别
        List<SysDictData> rankArray = DictUtils.getDictCache("item_rank");
        Map<String, String> rankMap = rankArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //不良等级
        List<SysDictData> badLevelArray = DictUtils.getDictCache("quality_bad_level");
        Map<String, String> badLevelMap = badLevelArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        for (QualityBadCategoryExport mouldModelExport : coCustomer) {

            QualityBadCategory qualityBadCategory = new QualityBadCategory();
            try {

                if (mouldModelExport.getBadName()==null||"".equals(mouldModelExport.getBadName())){
                    throw new GlobalException("不良名称不能为空");
                }

                if (mouldModelExport.getBadGrade()==null||"".equals(mouldModelExport.getBadGrade())){
                    throw new GlobalException("不良等级不能为空");
                }

                if (mouldModelExport.getItemRank()==null||"".equals(mouldModelExport.getItemRank())){
                    throw new GlobalException("检测阶别不能为空");
                }

                //获取不良类别编码
                String authorityCoding = feignService.getAuthorityCoding("quality:verifyconfig:badcategory:list");
                if (authorityCoding == null) {
                    throw new GlobalException("该单据未进行配置，无法生成单据编码");
                }
                // 赋值
                qualityBadCategory.setBadCode(authorityCoding)
                        .setBadName(mouldModelExport.getBadName())
                        .setBadContent(mouldModelExport.getBadContent());
                //不良等级
                for (Map.Entry<String, String> entry : badLevelMap.entrySet()) {
                    if (entry.getValue().equals(mouldModelExport.getBadGrade())) {
                        qualityBadCategory.setBadGrade(Integer.parseInt(entry.getKey()));
                        break;
                    }
                }
                //阶别
                for (Map.Entry<String, String> entry : rankMap.entrySet()) {
                    if (entry.getValue().equals(mouldModelExport.getItemRank())) {
                        qualityBadCategory.setItemRank(Integer.parseInt(entry.getKey()));
                        break;
                    }
                }
                qualityBadCategory.setCreateTime(new Date())
                        .setDeptId(SecurityUtils.getDeptId());

                save(qualityBadCategory);

                successNum++;
                successMsg.append(successNum + "、不良类别信息 " + mouldModelExport.getBadName() + " 导入成功");

            } catch (Exception e) {
                failureNum++;
                String msg = failureNum + "、不良类别 " + mouldModelExport.getBadName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new GlobalException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }

        return successMsg.toString();
    }
}
